package com.xyd.service;


import com.xyd.util.OutOfStockException;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;

@Component
@Aspect
public class LogAspect {

    @Before("p1()")
    public void before(JoinPoint jp) {
        Object[] args = jp.getArgs();
        String methodName = jp.getSignature().getName();

        if ("buyPhone".equals(methodName)) {
            System.out.println("日志：" + currTime() + "即将进行进货操作，数量" + args[0] + "部");
        }

        if ("salPhone".equals(methodName)) {
            System.out.println("日志：" + currTime() + "即将进行销售操作，数量" + args[0] + "部");
        }
    }

    @AfterReturning("p1()")
    public void afterReturning(JoinPoint jp) {
        String methodName = jp.getSignature().getName();

        if ("buyPhone".equals(methodName)) {
            System.out.println("日志：" + currTime() + "进货操作执行完毕");
        }

        if ("salPhone".equals(methodName)) {
            System.out.println("日志：" + currTime() + "销售工作执行完毕");
        }
    }

    @AfterThrowing(pointcut = "p1()", throwing = "e")
    public void afterThrowing(JoinPoint jp, OutOfStockException e) {
        String methodName = jp.getSignature().getName();
        System.out.println(currTime() + ":" + methodName + "执行的时候发生异常 " + e.getMessage());
    }


    @After("p1()")
    public void after(JoinPoint jp) {
        String methodName = jp.getSignature().getName();

        if ("buyPhone".equals(methodName)) {
            System.out.println("日志：" + currTime() + "进货操作执行完毕,发生异常也要执行");
        }

        if ("salPhone".equals(methodName)) {
            System.out.println("日志：" + currTime() + "销售工作执行完毕,发生异常也要执行");
        }
    }

    @Around("p1()")
    public Object aroundTest(ProceedingJoinPoint pjp) throws Throwable {
        String method = pjp.getSignature().getName();
        long begin = System.currentTimeMillis();

        try {
            return pjp.proceed();
        } finally {
            long end = System.currentTimeMillis();
            System.out.println("方法执行完毕，耗时：" + (end - begin) + "毫秒");
        }

    }

    @Pointcut("execution( void *Phone(int))")
    public void p1() {
    }


    public String currTime() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        return sdf.format(new Date());
    }
}
